<!-- 急救宣教组件 -->
<template>
  <div>
    <el-card>
      <!-- 面包屑导航区域 -->
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>急救自学</el-breadcrumb-item>
        <el-breadcrumb-item>急救宣教</el-breadcrumb-item>
        <!-- 新增按钮区域 -->
        <span class="btn">
          <el-button type="primary" size="medium" @click="addMissData()">新增</el-button>
          <!-- 批量删除按钮 -->
          <el-button type="danger" size="medium" @click="allDeleteBtn()">批量删除</el-button>
        </span>
      </el-breadcrumb>
      <span class="spnBorder"></span>
      <div class="serachFrom">
        <!-- <p>全部（{{this.total}}条）</p> -->
        <!-- 表单查询区域 -->
        <el-form :inline="true" :model="queryInfo" ref="queryFromRef" class="demo-form-inline">
          <el-form-item label="标题" prop="title">
            <el-input v-model="queryInfo.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="发布时间" prop="date">
            <el-date-picker
              v-model="queryInfo.date"
              type="daterange"
              value-format="yyyy-MM-dd"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item class="itemBtns">
            <el-button type="primary" @click="searchBtn">查询</el-button>
            <el-button @click="resetBtn">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        v-loading="pictLoading"
        element-loading-text="数据正在加载中..."
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
        <el-table-column prop="title" label="标题" align="center"></el-table-column>
        <el-table-column prop="moduleName" label="所属模块" align="center"></el-table-column>
        <el-table-column prop="publishTime" label="发布时间" align="center"></el-table-column>
        <el-table-column label="是否启用" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.state"
              :inactive-value="0"
              :active-value="1"
              class="switchStyle"
              active-text="启用"
              inactive-text="停用"
              @change="isEnable(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button type="primary" plain size="mini" @click="lookTableBtn(scope.row)">查看</el-button>
            <el-button type="primary" plain size="mini" @click="editMissData(scope.row)">修改</el-button>
            <el-button type="danger" plain size="mini" @click="deleteMissData(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 新增对话框 -->
    <el-dialog
      :title="flag===true?'新增':'修改'"
      :visible.sync="addMissionDialogVisible"
      width="60%"
      @close="resetFromData"
    >
      <!-- 新增表单区域 -->
      <el-form
        :label-position="labelPosition"
        label-width="120px"
        :model="addMissionDate"
        ref="MissionRef"
        :rules="MissionRules"
      >
        <el-form-item label="标题" prop="title" class="inputWidth">
          <el-input v-model="addMissionDate.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="所属模块" prop="moduleName" class="inputWidth inputRight">
          <el-select
            v-model="addMissionDate.moduleName"
            @change="selectMission($event)"
            placeholder="请选择所属模块"
          >
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime" class="inputWidth">
          <el-date-picker
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            v-model="addMissionDate.publishTime"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="state" class="inputWidth inputRight">
          <el-radio-group v-model="addMissionDate.state">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">不启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文章类型" prop="categoryName" class="inputWidth">
          <el-select
            v-model="addMissionDate.categoryName"
            @change="selectTypeName($event)"
            placeholder="请选择文章类型"
          >
            <el-option
              v-for="item in optionType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布内容" prop="content">
          <!-- <quill-editor
            v-model="addMissionDate.content"
            :options="editorOption"
            ref="myQuillEditor"
          ></quill-editor>-->
          <!-- <el-upload
            action="http://172.17.135.116:8089/rescue-map/common/oss/simple_upload"
            :on-success="upScuccess"
            :before-upload="beforeUpload"
            style="display:none"
          >
            <div ref="inputResult">7777</div>
          </el-upload>-->
          <editor
            v-model="addMissionDate.content"
            id="editor_id"
            height="300px"
            width="96%"
            :content.sync="editorText"
            :loadStyleMode="false"
            @on-content-change="onContentChange"
          ></editor>
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width:97%;">
          <el-input type="textarea" v-model="addMissionDate.remark"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <div class="dialogBot" slot="footer">
        <el-button @click="addMissionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addMissionBtn" :disabled="isDisable">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 查看对话框 -->
    <el-dialog title="查看" :visible.sync="lookMissionDialogVisible" width="60%">
      <!-- 表单区域 -->
      <el-form :label-position="labelPosition" label-width="120px" :model="addMissionDate">
        <el-form-item label="标题" class="inputWidth">
          <el-input v-model="addMissionDate.title" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属模块" class="inputWidth inputRight">
          <el-select v-model="addMissionDate.moduleName" placeholder="请选择" disabled>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" class="inputWidth">
          <el-date-picker
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            v-model="addMissionDate.publishTime"
            style="width: 100%;"
            disabled
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" class="inputWidth inputRight">
          <el-radio-group v-model="addMissionDate.state" disabled>
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">不启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文章类型" prop="categoryName" class="inputWidth">
          <el-select v-model="addMissionDate.categoryName" disabled>
            <el-option
              v-for="item in optionType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布内容" style="width:97%;">
          <!-- <quill-editor v-model="addMissionDate.content" disabled></quill-editor> -->
          <div
            style="border:1px solid #ccc;padding:10px;overflow: auto;max-height: 300px;"
            v-if="addMissionDate.content"
          >
            <div v-html="addMissionDate.content"></div>
          </div>
        </el-form-item>

        <el-form-item label="备注" style="width:97%;">
          <el-input type="textarea" v-model="addMissionDate.remark" disabled></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <div class="dialogBot" slot="footer">
        <el-button type="primary" @click="lookMissionDialogVisible = false">关 闭</el-button>
        <!-- <el-button @click="lookMissionDialogVisible = false">取 消</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import * as Quill from 'quill' // 引入编辑器
import editor from '../kindeditor.vue'

export default {
  components: {
    editor,
  },
  data() {
    return {
      // 要查询表单对象
      queryInfo: {
        page: 1,
        limit: 10,
        title: '',
        date: '',
      },
      // 表格数据对象
      tableData: [],
      total: 0,
      // 批量删除是的ids数组数据
      ids: [],
      // 默认设置新增和修改对话框隐藏
      addMissionDialogVisible: false,
      labelPosition: 'right',
      // 新增表单对象
      addMissionDate: {
        id: '',
        title: '',
        moduleName: '', // 所属模块
        moduleCode: '', // 所属模块code值
        categoryName: '', //文章类型名称
        category: '', //文章类型编码
        content: '',
        publishTime: '',
        state: '0', // 启用状态
        remark: '',
        ossKeys: '',
        sort: 2,
      },
      // 新增对话框下拉框选项
      options: [],
      // 对话框文章类型
      optionType: [],
      // 列表数据加载时loading
      pictLoading: false,
      // 控制添加或修改对话框标题显示
      flag: true,
      // 控制查看对话框的显示或隐藏
      lookMissionDialogVisible: false,
      // quill富文本编辑器显示
      // editorOption: {
      //   // Some Quill options...
      // },
      editorText: '', // 双向同步的变量
      content: '',
      htmlContent: '',
      // 成功上传后key值数组数据
      // ossKeyArr: [],
      // quill编辑器成功上传后文件根路径
      // rootPath: '',
      // 表单验证
      MissionRules: {
        title: [{ required: true, message: '请输入标题名称', trigger: 'blur' }],
        moduleName: [{ required: true, message: '请选择所属模块', trigger: 'change' }],
        content: [{ required: true, message: '请输入发布内容', trigger: 'blur' }],
        publishTime: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
      },
      isDisable: false, // 避免表单重复提交
    }
  },
  // 编辑框结束
  created() {
    this.getMissionList()
    this.getArticleType()
    this.getCheckAlldata()
  },
  methods: {
    onContentChange(val) {
      // console.log(val) // 编辑框的值
      this.addMissionDate.content = val
    },
    // ICON绑定事件
    // myQuillEditor() {
    //   if (this.$refs.myQuillEditor == undefined) {
    //     setTimeout(() => {
    //       // console.log(this.$refs.myQuillEditor)
    //       // 为图片ICON绑定事件  getModule 为编辑器的内部属性
    //       this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
    //       this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('video', this.videoHandler) // 为视频ICON绑定事件
    //     }, 1000)
    //   }
    // },
    // // 编辑框文件上传前
    // beforeUpload() {
    //   // console.log('imgload')
    // },
    // // 编辑框文件成功后获取 key 值
    // upScuccess(e, file, fileList) {
    //   console.log(e, fileList)
    //   if (e.errorCode !== 200) return this.$message.error('上传失败！')
    //   // fileList.map(v => {
    //   //   // console.log(v.response.data.key)
    //   //   return this.ossKeyArr.push(v.response.data.key)
    //   // })
    //   // console.log(this.ossKeyArr)
    //   // this.addMissionDate.ossKeys = this.ossKeyArr.toString()
    //   let url = this.rootPath + e.data.key
    //   this.addRange = this.$refs.myQuillEditor.quill.getSelection()
    //   // 调用编辑器的 insertEmbed 方法，插入URL
    //   this.$refs.myQuillEditor.quill.insertEmbed(this.addRange !== null ? this.addRange.index : 0, this.uploadType, url, Quill.sources.USER)
    // },
    // // 点击图片ICON触发事件
    // imgHandler(state) {
    //   console.log('image')
    //   this.$refs.inputResult.click()
    //   // 再次点击图片或视频清空 key值数组
    //   // this.ossKeyArr = []
    //   // if (state) {
    //   //   let fileInput = document.getElementById('imgInput')
    //   //   fileInput.click() // 加一个触发事件
    //   // }
    //   this.uploadType = 'image' //图片类型
    //   this.rootPath = 'http://172.17.135.169:8089/rescue-map/common/oss/idaas_show_image?key='
    // },
    // // 点击视频ICON触发事件
    // videoHandler(state) {
    //   console.log('video')
    //   this.$refs.inputResult.click()
    //   // this.ossKeyArr = []
    //   this.uploadType = 'video'
    //   this.rootPath = ' http://172.17.135.169:8089/rescue-map/common/oss/idaas_show_video?key='
    // },
    // 获取数据列表
    async getMissionList() {
      this.pictLoading = true
      let datas = { page: this.queryInfo.page, limit: this.queryInfo.limit, title: this.queryInfo.title, startTime: this.queryInfo.date[0], endTime: this.queryInfo.date[1] }
      const { data: res } = await this.$http.get('/sys/rescue_knowledge/list_page', { params: datas })
      // console.log(res)
      this.pictLoading = false
      if (res.errorCode !== 200) return this.$message.error('获取数据列表失败！')
      this.tableData = res.data.list
      this.total = res.data.totalCount
    },
    handleCurrentChange(currentPage) {
      this.queryInfo.page = currentPage
      this.getMissionList()
    },
    handleSizeChange(pageSize) {
      this.queryInfo.limit = pageSize
      this.getMissionList()
    },
    // 获取文章类型数据
    async getArticleType() {
      const { data: res } = await this.$http.get('sys/dict/getDict?code=type')
      // console.log(res.data)
      this.optionType = res.data
    },
    // 监听文章类型菜单的变化
    selectTypeName(id) {
      // console.log(id)
      this.optionType.find((item) => {
        if (item.id === id) {
          this.addMissionDate.categoryName = item.name
          this.addMissionDate.category = item.code
        }
      })
    },
    // 监听表格是否启用按钮的变化
    async isEnable(rowData) {
      // console.log(rowData)
      const { data: res } = await this.$http.put('/sys/rescue_knowledge/updateState', { id: rowData.id, state: rowData.state, sort: 2 })
      if (res.errorCode !== 200) return this.$message.error('状态修改失败！')
      this.$message.success('状态修改成功！')
      this.getMissionList()
    },
    // 获取对话框所属模块数据
    async getCheckAlldata() {
      const { data: res } = await this.$http.get('/sys/dict/getDict', { params: { code: 'rescuemodule' } })
      if (res.errorCode !== 200) return this.$message.error('获取模块数据失败！')
      this.options = res.data
    },
    // 监听所属模块下拉菜单变化
    selectMission(id) {
      // console.log(id)
      this.options.find((item) => {
        if (item.id === id) {
          this.addMissionDate.moduleName = item.name
          this.addMissionDate.moduleCode = item.code
        }
      })
    },
    // 点击新增按钮显示对话框
    addMissData() {
      // this.myQuillEditor()
      this.addMissionDialogVisible = true
      this.flag = true
      this.addMissionDate.id = ''
      this.addMissionDate.title = ''
      this.addMissionDate.moduleName = ''
      this.addMissionDate.categoryName = ''
      this.addMissionDate.content = ''
      this.editorText = ''
      this.addMissionDate.publishTime = ''
      this.addMissionDate.state = 0
      this.addMissionDate.remark = ''
    },
    // 点击修改按钮显示对话框
    editMissData(Row) {
      console.log(Row)
      // this.myQuillEditor()
      this.addMissionDialogVisible = true
      this.flag = false
      this.addMissionDate.id = Row.id
      this.addMissionDate.title = Row.title
      this.addMissionDate.moduleName = Row.moduleName
      this.addMissionDate.categoryName = Row.categoryName
      this.addMissionDate.content = Row.content
      this.htmlContent = Row.content
      this.editorText = Row.content
      this.addMissionDate.publishTime = Row.publishTime
      this.addMissionDate.state = Row.state
      this.addMissionDate.remark = Row.remark
    },
    // 实现新增和修改功能
    addMissionBtn() {
      if (this.flag) {
        // 表单预检验
        this.$refs.MissionRef.validate(async (valid) => {
          // console.log(valid)
          if (!valid) return
          this.isDisable = true
          const { data: res } = await this.$http.post('/sys/rescue_knowledge/save', this.addMissionDate)
          this.isDisable = false
          // console.log(res)
          if (res.errorCode !== 200) return this.$message.error('添加数据失败！')
          this.$message.success('添加数据成功！')
          this.getMissionList()
          this.addMissionDialogVisible = false
        })
      } else {
        this.$refs.MissionRef.validate(async (valid) => {
          if (!valid) return
          this.isDisable = true
          const { data: res } = await this.$http.put('/sys/rescue_knowledge/update', this.addMissionDate)
          this.isDisable = false
          if (res.errorCode !== 200) return this.$message.error('修改数据失败！')
          this.$message.success('修改数据成功！')
          this.getMissionList()
          this.addMissionDialogVisible = false
        })
      }
    },
    // 监听对话框关闭事件重置表单
    resetFromData() {
      this.$refs.MissionRef.resetFields()
    },
    // 实现删除功能
    async deleteMissData(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err)
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/sys/rescue_knowledge/delete', { data: { ids: id } })
      if (res.errorCode !== 200) return this.$message.error('删除数据失败！')
      this.$message.success('删除数据成功！')
      //此时已经实现删除操作，所以total的值需要减1，Math.ceil是向上取整，保证始终大于等于1
      const totalPage = Math.ceil((this.total - 1) / this.queryInfo.limit)
      //记录当前页码、记住删除最后一条数据时当前码是最后一页
      const pagenum = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page
      //实现跳转
      this.queryInfo.page = pagenum < 1 ? 1 : pagenum
      // console.log(this.queryInfo.page)
      // 重新渲染（后面方法改为你的方法名）
      this.getMissionList()
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      // console.log(val)
      let ids = []
      val.map(function (v) {
        ids.push(v.id)
      })
      this.ids = ids
    },
    // 实现批量删除功能
    async allDeleteBtn() {
      console.log(this.ids)
      if (this.ids.length == 0) return this.$message.info('请先勾选要删除的数据！')
      let params = { ids: this.ids }
      const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/sys/rescue_knowledge/delete', { data: params })
      if (res.errorCode !== 200) return this.$message.error('删除数据失败！')
      this.$message.success('删除数据成功！')
      // totalPage 表示为删除n条数据除以每页显示的条数后、得出最后一页页数
      const totalPage = Math.ceil((this.total - this.ids.length) / this.queryInfo.limit)
      const pagenum = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page
      //实现跳转
      this.queryInfo.page = pagenum < 1 ? 1 : pagenum
      this.getMissionList()
    },
    // 查看功能
    lookTableBtn(Row) {
      console.log(Row)
      this.lookMissionDialogVisible = true
      this.addMissionDate.title = Row.title
      this.addMissionDate.moduleName = Row.moduleName
      this.addMissionDate.categoryName = Row.categoryName
      this.addMissionDate.content = Row.content
      this.addMissionDate.publishTime = Row.publishTime
      this.addMissionDate.state = Row.state
      this.addMissionDate.remark = Row.remark
    },
    // 表单查询功能
    async searchBtn() {
      this.queryInfo.page = 1
      this.queryInfo.limit = 10
      this.getMissionList()
    },
    // 实现重置功能
    resetBtn() {
      this.$refs.queryFromRef.resetFields()
      this.searchBtn()
    },
  },
}
</script>
<style lang="less" scoped>
.el-card {
  .spnBorder {
    display: block;
    margin: 15px 0;
    width: 100%;
    border-bottom: 1px solid #ccc;
  }
  .serachFrom {
    margin-left: 30px;
    p {
      padding: 15px 0;
    }
    .el-form-item {
      margin-right: 30px;
    }
  }
  .el-pagination {
    float: right;
    margin: 10px 20px;
  }
}
.el-dialog {
  .dialogBot {
    text-align: right !important;
    padding-right: 3%;
  }
  .el-select {
    width: 100%;
  }
  // 编辑框
  // .quill-editor {
  //   height: 160px;
  //   padding-bottom: 100px;
  //   .ql-snow .ql-picker.ql-size .ql-picker-label::before,
  //   .ql-snow .ql-picker.ql-size .ql-picker-item::before {
  //     content: '14px' !important;
  //   }
  // }
}
</style>